#!/usr/bin/env python
#coding:utf-8
from min_p import *
reload(sys)
sys.setdefaultencoding("utf-8")

from selenium import webdriver  
from selenium.webdriver.common.action_chains import ActionChains
from taobao_login import TAOBAO_LOGIN
from taobao_db import TB_DB

#淘宝获取订单数据
class TAOBAO_TRADE(TAOBAO_LOGIN):
    #打开订单页面
    def get_trades_list(self):
        try:
            self.driver.get("https://trade.taobao.com/trade/itemlist/list_sold_items.htm")
        except Exception, e:
            print e
            return log_wrong()

    #获取当前页的订单[订单编号1+订单时间,订单编号2+订单时间]
    def get_trades(self):
        try:
            order_fast_list=[]
            trades = self.driver.find_elements_by_class_name("item-mod__checkbox-label___cRGUj")
            #taobao_id = self.driver.find_elements_by_class_name("buyer-mod__name___S9vit")
            for i in range(len(trades)):
                order_id,order_time = trades[i].text.split("成交时间: ")
                order_id = order_id.replace("订单号: ","")
                order_fast_list.append("%s+%s"%(order_id,order_time))#,"buyer_name":taobao_id[i].text})
            print order_fast_list
            return order_fast_list
        except Exception, e:
            print e
            return log_wrong()

    #获取订单详情
    def get_trade_info(self,order_id):
        try:
            self.driver.get("https://trade.taobao.com/trade/detail/trade_order_detail.htm?biz_order_id=%s"%order_id)
            order_data = self.driver.page_source
            json_data = json.loads(re_one('(?<=JSON.parse\(\').+(?=\'\);)',order_data).replace('\\\"','"'))
            print json_data
            return json_data
        except Exception, e:
            print e
            return log_wrong()

    #获取订单列表[{订单编号1:{订单1信息}},{订单编号2:{订单2信息}}]
    def get_order_dic(self):
        try:
            order_dic = {}
            order_list = []
            states = self.driver.find_elements_by_class_name("text-mod__link___2PH1j")
            trades = self.driver.find_elements_by_class_name("item-mod__checkbox-label___cRGUj")
            taobao_id = self.driver.find_elements_by_class_name("buyer-mod__name___S9vit")
            for i in range(len(trades)):
                order_id,order_time = trades[i].text.split("成交时间: ")
                order_id = order_id.replace("订单号: ","")
                order_list.append(order_id)
                order_dic[order_id]={"buyer_name":taobao_id[i].text,"order_creat_time":order_time,"outer_iid":"","refund":"","order_state":""}
            for i in states:
                state_text = i.text
                state_id = i.get_attribute("data-reactid").split("$")[1].split(".")[0]
                if state_text in ["等待买家付款","关闭交易","买家已付款","交易成功","卖家已发货"]:
                    order_dic[state_id]["order_state"]=state_text
            msg = driver.find_elements_by_class_name("trade-order-main")
            for i in msg:
                order_id = i.text.split("\n")[0].split(u"成交时间")[0].split(u": ")[1]
                for ss in i.text.split("\n"):
                    if "商家编码" in ss:
                        order_dic[order_id]["outer_iid"]=ss.split("：")[-1]
                    elif "退款成功" in ss:
                        order_dic[order_id]["refund"]=u"退款成功"
                    elif "请卖家处理" in ss:
                        order_dic[order_id]["refund"]=u"请卖家处理"
                    else:pass
            order_list_all = []
            for i in order_list:
                order_list_all.append({i:order_dic[i]})
            return order_list_all
        except Exception, e:
            print e
            return log_wrong()

    def next_page(self):
		try:
			buttons = self.driver.find_elements_by_tag_name("button")#.get_attribute('disabled')
			for button in buttons:
				if "下一页" in button.text:
					if button.get_attribute('disabled')==None:
						button.click()
						time.sleep(3)
						return True
					else:
						return False
		except Exception, e:
			print e
			return log_wrong()
